package com.woniuxy.user.controller;

import com.woniuxy.entity.Perm;
import com.woniuxy.entity.Role;
import com.woniuxy.user.service.RoleService;
import com.woniuxy.utils.ResponseResult;
import com.woniuxy.utils.ResultStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    RoleService roleService;

    @GetMapping("/all")
    public List<Role> getAllRoles(){
        return roleService.getAllRoles();
    }

    @GetMapping("/allRoles")
    public List<String> getRoles(){
        List<String> roles = new ArrayList<>();
        roleService.getAllRoles().forEach(e->{
            roles.add(e.getRolename());
        });
        return roles;
    }

    @GetMapping("/get")
    public Role getRole(Integer rid){
        List<String> perms = new ArrayList<>();
        Role role = roleService.getRole(rid);
        role.getPermissions().forEach(e->perms.add(e.getPermname()));
        role.setPerms(perms);
        return role;
    }

    @GetMapping("/getByName")
    public List<Role> getRoleByName(String rolename){
        return roleService.getRoleByName(rolename);
    }

    @PostMapping("/add")
    public ResponseResult addRole(@RequestBody Perm perms){
        System.out.println(perms);
        Role role = new Role();
        role.setRolename(perms.getRolename());
        roleService.addRole(role);
        int rid = role.getId();
        roleService.updateRoleAndPermissions(rid, perms.getPerms());
        return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS,"角色添加成功",null);
    }

    /**
     * 修改权限
     * @param perms
     * @return
     */
    @PostMapping("/updatePermissions")
    public ResponseResult changePermissions(@RequestBody Perm perms){
        roleService.updateRoleAndPermissions(perms.getRid(), perms.getPerms());
        return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS,"权限修改成功",null);
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    public ResponseResult delUser(@PathVariable("id") int id){
        try {
            System.out.println(id);
            roleService.deleteRole(id);
            return new ResponseResult(200, ResultStatus.REQUEST_SUCCESS, "删除成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(500, ResultStatus.REQUEST_FAILED, "删除失败", null);
        }
    }
}
